//
//  PSmallLight.m
//  ProjectL
//
//  Created by Nguyen Tan Loc on 8/16/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "PSmallLight.h"
#import "PLine.h"
#import "LevelManager.h"

@implementation PSmallLight

-(id) initWithLine:(PLine *)line
{
    if (self = [super initWithSpriteFrameName:[self getSpriteFrameName]])
    {
        mLine = line;
        [self setScale:0.4];
        [self setColor:[[LevelManager getInstance] getWorldColor]];
        [self setPosition:[mLine getPosWithPercent:0]];
        [self setVisible:NO];
    }
    
    return self;
}

-(void) update:(ccTime)delta
{
//    CCLOG(@"mstate = %d", mState);
    if (mState == eSLS_DELAY)
    {
        mAppearDelayTime -= delta;
        if (mAppearDelayTime <= 0)
        {
            mState = eSLS_APPEAR;
        }
    }
    else if (mState == eSLS_APPEAR)
    {
        int opacity = self.opacity + 10;
        if (opacity >= 255)
        {
            opacity = 255;
            mState = eSLS_MOVING;
        }
        [self setOpacity:opacity];
    }
    else if (mState == eSLS_MOVING)
    {
        mTransferPercent += delta * 50;
        if (mTransferPercent > 100.0f)
        {
            mTransferPercent = 100.0f;
            mState = eSLS_DISAPPEAR;
        }
    }
    else if (mState == eSLS_DISAPPEAR)
    {
        int opacity = self.opacity - 10;
        if (opacity <= 0)
        {
            opacity = 0;
            [self resetLight];
            mState = eSLS_DELAY;
        }
        [self setOpacity:opacity];
    }
    
    [self setPosition:[mLine getPosWithPercent:mTransferPercent]];
}

-(void) resetLight
{
    mState = eSLS_DELAY;
    mAppearDelayTime = CCRANDOM_0_1() * 2;
    mTransferPercent = 0;
    [self setPosition:mLine._node.position];
    [self setOpacity:0];
}

-(void) addActions:(NSArray *)actions
{
    
}

-(void) startAction
{
    [self resetLight];
    [self scheduleUpdate];
    [self setVisible:YES];
}

-(void) stopAction
{
    [self unscheduleUpdate];
}

-(NSString *) getSpriteFrameName
{
    return SFN_PLIGHT;
}

-(void) dealloc
{
    [super dealloc];
    
    CCLOG(@"PSmallLight dealloc!");
}

@end
